package api.base.observer;

import android.app.Activity;
import android.content.Context;
import android.net.ParseException;
import android.support.v7.app.AlertDialog;
import android.util.Log;

import com.google.gson.JsonParseException;

import org.json.JSONException;

import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.UnknownHostException;

import api.utils.ToastUtils;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

/**
 * Created by Administrator on 2018-01-15.
 */

public abstract class DefaultNoParamsObserver<T> implements Observer<T> {
    private Context context;

    //  Activity 是否在执行onStop()时取消订阅
    private boolean isAddInStop = false;
    private AlertDialog sAlertDialog;

    public DefaultNoParamsObserver(Context activity) {

        this.context = activity;
//        showDialog();
    }

//    protected void showDialog() {
//        sAlertDialog = new AlertDialog.Builder(context).create();
//        sAlertDialog.show();            //alertDialog.cancel();关闭
//        Window win = sAlertDialog.getWindow();
//        // 点击外部区域不会消失
//        sAlertDialog.setCanceledOnTouchOutside(false);
//        //设置窗口透明#00000000，要不出问题
//        win.setBackgroundDrawableResource(R.color.color_tran);
//        WindowManager.LayoutParams lp = win.getAttributes();
//        win.setGravity(Gravity.CENTER);//最终位置Gravity.LEFT | Gravity.BOTTOM，，，，，top,right,中间
//        // lp.alpha = 0.7f;//改变的是整个窗口，最好不要
//        lp.width = lp.WRAP_CONTENT;//宽和屏幕宽一样
//        lp.height = lp.WRAP_CONTENT;//设置dialog高度为包裹内容
//
//        //lp.x =-80向左偏移80，lp.y =-60上偏移60
//        win.getDecorView().setPadding(0, 0, 0, 0);//去padding，要不然不会跟父窗体一样宽
////增加一点视觉效果
//        win.clearFlags
//                (WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
//        win.setAttributes(lp);
//        win.setContentView(R.layout.dialog);
////找到里面的控件
//        win.setWindowAnimations(R.style.take_photo_anim);
//    }


    public DefaultNoParamsObserver(Activity activity, boolean isShowLoading) {
        this.context = activity;
//        if (isShowLoading)
//            showDialog();
    }


    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(T response) {
//        dismissProgress();
        onSuccess(response);
//        if (response.getDesc().toString().equals("OK")) {
//        } else {
//            onFail(response);
//        }
        /*if (response.getCode() == 200) {
            onSuccess(response);
        } else {
            onFail(response);
        }*/
    }

    private void dismissProgress() {
        sAlertDialog.cancel();

    }

    @Override
    public void onError(Throwable e) {
        Log.e("DefaultObserver", e.getMessage());
//        dismissProgress();
        if (e instanceof HttpException) {     //   HTTP错误
            onException(ExceptionReason.BAD_NETWORK);
        } else if (e instanceof ConnectException
                || e instanceof UnknownHostException) {   //   连接错误
            onException(ExceptionReason.CONNECT_ERROR);
        } else if (e instanceof InterruptedIOException) {   //  连接超时
            onException(ExceptionReason.CONNECT_TIMEOUT);
        } else if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {   //  解析错误
            onException(ExceptionReason.PARSE_ERROR);
        } else {
            onException(ExceptionReason.UNKNOWN_ERROR);
        }
    }

    @Override
    public void onComplete() {
    }

    /**
     * 请求成功
     *
     * @param response 服务器返回的数据
     */
    abstract public void onSuccess(T response);

    /**
     * 服务器返回数据，但响应码不为200
     *
     * @param response 服务器返回的数据
     */
    public void onFail(T response) {
//        int message = response.getStatus();
//        if (message != 1000) {
//            ToastUtils.show(context, "服务器炸了");
//        }
    }

    /**
     * 请求异常
     *
     * @param reason
     */
    public void onException(ExceptionReason reason) {
        switch (reason) {
            case CONNECT_ERROR:
                ToastUtils.show(context, "连接错误");
                break;

            case CONNECT_TIMEOUT:
                ToastUtils.show(context, "连接超时");
                break;

            case BAD_NETWORK:
                ToastUtils.show(context, "网络问题");
                break;

            case PARSE_ERROR:
                ToastUtils.show(context, "解析数据失败");
                break;

            case UNKNOWN_ERROR:
            default:
                ToastUtils.show(context, "未知错误");
                break;
        }
    }

    /**
     * 请求网络失败原因
     */
    public enum ExceptionReason {
        /**
         * 解析数据失败
         */
        PARSE_ERROR,
        /**
         * 网络问题
         */
        BAD_NETWORK,
        /**
         * 连接错误
         */
        CONNECT_ERROR,
        /**
         * 连接超时
         */
        CONNECT_TIMEOUT,
        /**
         * 未知错误
         */
        UNKNOWN_ERROR,
    }
}
